package com.sinotrans.common.config;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.http.HttpHeaders;

import com.sinotrans.common.constant.Constant;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

public abstract class AbstractSwaggerConfig {

	public Docket createApi() {
		return new Docket(DocumentationType.OAS_30).pathMapping("/").enable(true)
				// info
				.apiInfo(apiInfo())
				// basePackage
				.select().apis(RequestHandlerSelectors.basePackage(basePackage())).paths(PathSelectors.any()).build()
				.securitySchemes(securitySchemes()).securityContexts(securityContexts()).protocols(protocols());
	}

	protected String basePackage() {
		String className = AbstractSwaggerConfig.class.getName();
		String[] packages = className.split("\\.");
		return packages[0] + "." + packages[1];
	}

	protected Set<String> protocols() {
		Set<String> protocols = new HashSet<String>();
		protocols.add("http");
		protocols.add("https");
		return protocols;
	}

	protected List<SecurityScheme> securitySchemes() {
		ArrayList<SecurityScheme> apiKeys = new ArrayList<>();
		apiKeys.add(new ApiKey(HttpHeaders.AUTHORIZATION, HttpHeaders.AUTHORIZATION, Constant.HEADER));
		return apiKeys;
	}

	protected List<SecurityContext> securityContexts() {
		List<SecurityContext> securityContextList = new ArrayList<>();
		List<SecurityReference> securityReferenceList = new ArrayList<>();
		securityReferenceList.add(new SecurityReference(HttpHeaders.AUTHORIZATION, scopes()));
		securityContextList.add(SecurityContext.builder().securityReferences(securityReferenceList).build());
		return securityContextList;
	}

	protected AuthorizationScope[] scopes() {
		return new AuthorizationScope[] { new AuthorizationScope("global", "accessAnything") };
	}

	protected abstract ApiInfo apiInfo();

}
